const { getDb } = require('../database');

class UserModel {
  /**
   * 获取所有用户
   * @returns {Promise<Array>} 用户列表
   */
  static async getAllUsers() {
    const db = await getDb();
    return db.all('SELECT * FROM users');
  }

  /**
   * 根据ID获取用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object|null>} 用户信息
   */
  static async getUserById(id) {
    const db = await getDb();
    return db.get('SELECT * FROM users WHERE id = ?', [id]);
  }

  /**
   * 根据用户名获取用户
   * @param {string} username - 用户名
   * @returns {Promise<Object|null>} 用户信息
   */
  static async getUserByUsername(username) {
    const db = await getDb();
    return db.get('SELECT * FROM users WHERE username = ?', [username]);
  }

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<number>} 新创建的用户ID
   */
  static async createUser(userData) {
    const { username, password, nickname, avatar, type, organization_id } = userData;
    const db = await getDb();
    const result = await db.run(
      'INSERT INTO users (username, password, nickname, avatar, type, organization_id) VALUES (?, ?, ?, ?, ?, ?)',
      [username, password, nickname, avatar, type, organization_id]
    );
    return result.lastID;
  }

  /**
   * 更新用户信息
   * @param {number} id - 用户ID
   * @param {Object} userData - 用户数据
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updateUser(id, userData) {
    const { username, password, nickname, avatar, type, organization_id } = userData;
    const db = await getDb();
    const result = await db.run(
      'UPDATE users SET username = ?, password = ?, nickname = ?, avatar = ?, type = ?, organization_id = ? WHERE id = ?',
      [username, password, nickname, avatar, type, organization_id, id]
    );
    return result.changes > 0;
  }

  /**
   * 删除用户
   * @param {number} id - 用户ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async deleteUser(id) {
    const db = await getDb();
    const result = await db.run('DELETE FROM users WHERE id = ?', [id]);
    return result.changes > 0;
  }
}

module.exports = UserModel;